package com.shop.autoshop.pay.wxpay;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayOrderQueryRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;
import java.math.BigDecimal;

/**
 * @version: 1.0.1
 * @author: lyt
 * @description: 支付示例-后端接口服务->微信支付 -> 微信支付
 **/

@Slf4j
@Service
public class WxpayServiceImpl implements WxpayService {


    @Resource
    private WxPayProperty wxPayProperty;

    @Resource
    private WxPayConfiguration wxPayConfiguration;

    @Resource
    private HttpServletRequest request;

    /**
     * 微信支付下单
     *
     * @param wxpayCreateBean
     * @return WxpayOrderCreate
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WxPayUnifiedOrderResult orderPreCreate(WxpayCreateBean wxpayCreateBean) {

        String spbillCreateIp = wxPayConfiguration.getRemoteHost(request);
        WxPayUnifiedOrderRequest orderRequestequest = WxPayUnifiedOrderRequest.newBuilder()
                .body(wxpayCreateBean.getBody())
                .outTradeNo(wxpayCreateBean.getOutTradeNo())
                .totalFee(new BigDecimal(wxpayCreateBean.getTotalFee()).multiply(new BigDecimal("100")).intValue())
                .spbillCreateIp(spbillCreateIp)
                .notifyUrl(wxPayProperty.getNotifyUrl())
                .tradeType(wxpayCreateBean.getTradeType())
                .productId(wxpayCreateBean.getProductId())
                .attach(wxpayCreateBean.getStoreId())
                .build();

        WxPayUnifiedOrderResult result = null;
        try {
            result = wxPayConfiguration.getWxPayService().unifiedOrder(orderRequestequest);
            log.info("wxpay create order :{}", JSON.toJSONString(result));
            if (result.getReturnCode().equals("SUCCESS")&& result.getResultCode().equals("SUCCESS")) {
                return result;
            }else{
                throw new RuntimeException("微信创建订单失败:" +result.getErrCodeDes());
            }
        } catch (WxPayException e) {
            log.error("微信创建订单失败:{}", e.getMessage());
            log.error("微信创建订单失败:{}", e.fillInStackTrace());
            if (result != null) {
                throw new RuntimeException("微信创建订单失败:" + result.getErrCodeDes());
            }else{
                throw new RuntimeException("微信创建订单失败:" + e.getErrCodeDes());
            }
        }

    }

    @Override
    public WxPayOrderQueryResult orderQuery(String orderNum) {
        WxpayTradeBean wxpayTradeBean = new WxpayTradeBean();
        wxpayTradeBean.setOutTradeNo(orderNum);
        return this.tradeQuery(wxpayTradeBean);
    }

    public WxPayOrderQueryResult tradeQuery(WxpayTradeBean wxpayTradeBean) {
        WxPayOrderQueryRequest build = WxPayOrderQueryRequest.newBuilder()
                .outTradeNo(wxpayTradeBean.getOutTradeNo())
                .transactionId(wxpayTradeBean.getTransactionId()).build();
        try {
            WxPayOrderQueryResult wxPayOrderQueryResult = wxPayConfiguration.getWxPayService().queryOrder(build);
            log.info("order:{}",wxpayTradeBean.getOutTradeNo());
            log.info("WxPayOrderQueryResult:{}",JSON.toJSONString(wxPayOrderQueryResult));
            if (wxPayOrderQueryResult.getReturnCode().equals("SUCCESS")&& wxPayOrderQueryResult.getResultCode().equals("SUCCESS")) {
                return wxPayOrderQueryResult;
            }
            return null;
        } catch (WxPayException e) {
            log.error("微信订单查询异常:{}", e.getMessage());
            return null;
        }
    }

    @Override
    public WxPayOrderNotifyResult notify(String xmlData) {
        try {
            //从xml先解析出customerId
            WxpayNotifyBean wxpayNotifyBean = WxpayNotifyBean.xmlToBean(xmlData);
            Integer customerId =Integer.valueOf(wxpayNotifyBean.getAttach());
            final WxPayOrderNotifyResult notifyResult = wxPayConfiguration.getWxPayService().parseOrderNotifyResult(xmlData);
            return  notifyResult;
        }catch (WxPayException e){
            log.error("微信通知异常：{}",e.getMessage());
        } catch (JAXBException e) {
            log.error("微信通知xml转换异常：{}",e.getMessage());
        }
        return null;
    }
}
